package com.ps.pspreview;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class BitmapUtils {
	/**
	 * This takes components that are already in pre multiplied form, and
	 * packs them into an int in the correct device order.
	 */
	private static int pack8888(int r, int g, int b, int a) {
		return (r << 0) | ( g << 8) | (b << 16) | (a << 24);
	}
	
	/** convert an unsigned byte to an integer */
	private static int unsignedByteToInt(byte b) {
		return (int) b & 0xFF;
	}
	
	
	/**
	 * The thread has called us with the bytes from Photoshop
	 * Make a Bitmap from the Pixmap
	 * @param inBytes
	 * @param inIndexer
	 * @return error messages as String
	 */
	public static Bitmap createBitmap(byte [] inBytes, int inIndexer) {
		Bitmap mBitmap = null;
		int width =    (inBytes[inIndexer++] << 24) + ((inBytes[inIndexer++] & 0xFF) << 16) + ((inBytes[inIndexer++] & 0xFF) << 8) + (inBytes[inIndexer++] & 0xFF);
		int height =   (inBytes[inIndexer++] << 24) + ((inBytes[inIndexer++] & 0xFF) << 16) + ((inBytes[inIndexer++] & 0xFF) << 8) + (inBytes[inIndexer++] & 0xFF);
		int rowBytes = (inBytes[inIndexer++] << 24)	+ ((inBytes[inIndexer++] & 0xFF) << 16)	+ ((inBytes[inIndexer++] & 0xFF) << 8) + (inBytes[inIndexer++] & 0xFF);
		byte colorMode = inBytes[inIndexer++];
		if (1 != colorMode) return null;
		byte channelCount = inBytes[inIndexer++];
		if (1 != channelCount && 3 != channelCount) return null;
		byte bitsPerChannel = inBytes[inIndexer++];
		if (8 != bitsPerChannel) return null;
		int extra = rowBytes - width * channelCount;
		mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		for (int y = 0; y < height; y++, inIndexer += extra) {
			for (int x = 0; x < width; x++) {
				int color = 0;
				// 1 or 3 for now
				if (channelCount == 1) {
					color = pack8888(inBytes[inIndexer], inBytes[inIndexer], inBytes[inIndexer], 255);
					inIndexer++;
				} else {
					color = pack8888(unsignedByteToInt(inBytes[inIndexer + 2]), unsignedByteToInt(inBytes[inIndexer + 1]), unsignedByteToInt(inBytes[inIndexer]), 255);
					inIndexer += 3;
				}
				mBitmap.setPixel(x, y, color);
			}
		}
		return mBitmap;
	}

	/**
	 * The thread has called us with a JPEG from Photoshop
	 * Make a Bitmap from the JPEG bytes
	 * @param inBytes
	 * @param inIndexer
	 * @return error messages as String
	 */
	public static Bitmap createBitmapFromJPEG(byte [] inBytes, int inIndexer) {
		return BitmapFactory.decodeByteArray(inBytes, inIndexer, inBytes.length - inIndexer);
	}
}
